package com.zhongxi.guoyuan.OffLineShop.UI;

import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Handler;
import android.os.Message;
import android.support.v7.widget.Toolbar;
import android.text.Editable;
import android.text.Html;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.util.Xml;
import android.view.KeyEvent;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RatingBar;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.alipay.sdk.app.PayTask;
import com.tencent.mm.opensdk.modelpay.PayReq;
import com.tencent.mm.opensdk.openapi.IWXAPI;
import com.tencent.mm.opensdk.openapi.WXAPIFactory;
import com.zhongxi.guoyuan.OffLineShop.ConnectNet.NetWork;
import com.zhongxi.guoyuan.OffLineShop.Model.PayInfo;
import com.zhongxi.guoyuan.OffLineShop.UrlOffLine.RelativeUrl;
import com.zhongxi.guoyuan.R;
import com.zhongxi.guoyuan.application.MyApplication;
import com.zhongxi.guoyuan.entity.BaseResponse;
import com.zhongxi.guoyuan.entity.pay.PayAliPayData;
import com.zhongxi.guoyuan.entity.pay.WeixinData;
import com.zhongxi.guoyuan.entity.user.center.UserExtendResult;
import com.zhongxi.guoyuan.url.Url;
import com.zhongxi.guoyuan.utils.CommonTool;
import com.zhongxi.guoyuan.utils.DataUtil;
import com.zhongxi.guoyuan.utils.DesTool;
import com.zhongxi.guoyuan.utils.MD5Tool;
import com.zhongxi.guoyuan.utils.SpUtils;
import com.zhongxi.guoyuan.utils.ToastUtil;
import com.zhongxi.guoyuan.utils.UiUtils;
import com.zhongxi.guoyuan.view.HtmlActivity;
import com.zhongxi.guoyuan.view.MainHomeActivity;
import com.zhongxi.guoyuan.view.PaySuccessActivity;
import com.zhongxi.guoyuan.weixin.MD5;
import com.zhongxi.guoyuan.weixin.Util;
import com.zhongxi.guoyuan.zhifubao.PayResult;
import com.zhongxi.guoyuan.zhifubao.SignUtils;

import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONObject;
import org.xmlpull.v1.XmlPullParser;

import java.io.StringReader;
import java.math.BigDecimal;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Random;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;
import io.reactivex.ObservableSource;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Consumer;
import io.reactivex.functions.Function;
import io.reactivex.schedulers.Schedulers;

public class SurePayActivity extends OffLineBaseActivity {

    @Bind(R.id.toolbar)
    Toolbar mToolbar;
    @Bind(R.id.tv_name)
    TextView mTvName;
    @Bind(R.id.tv_distance)
    TextView mTvDistance;
    @Bind(R.id.tv_sure_money)
    TextView mTvSureMoney;
    @Bind(R.id.tv_incentive_meidou)
    TextView mTvIncentiveMeidou;
    @Bind(R.id.tv_hongdou)
    TextView mTvHongdou;
    @Bind(R.id.tv_notes)
    TextView mTvNotes;
    @Bind(R.id.et_secret)
    EditText mEtSecret;
    @Bind(R.id.bt_sure_pay)
    Button mBtSurePay;
    @Bind(R.id.tv_declare)
    TextView mTvDeclare;
    @Bind(R.id.tv_money)
    TextView mTvMoney;
    @Bind(R.id.tv_no_pay)
    TextView mTvNoPay;
    @Bind(R.id.ll_meidou)
    LinearLayout mLlMeiDou;
    @Bind(R.id.iv_weixin)
    ImageView mIvWeixin;
    @Bind(R.id.iv_zhifubao)
    ImageView mIvZhifubao;
    @Bind(R.id.rl_sure_moey)
    RelativeLayout mRlSureMoey;
    @Bind(R.id.ll_secret_pay)
    LinearLayout mLlSecretPay;
    private String hongdou = "0";
    private String money = "0";
    private String mPaysecret;
    private String mNotes = "";
    private String mMoney;
    private String mTrim = "";
    private String mShopid;
    private PayAliPayData aliPayData;
    private WeixinData weixinData;
    private String mChecksum;
    private String mOrderid;
    private String mUd;
    private String mName;
    private String mMeidou;

    @Override
    protected void init() {
        super.init();
        setContentView(R.layout.activity_sure_pay);
        ButterKnife.bind(this);
    }

    /*初始化anctionbar*/
    @Override
    protected void initActionBar() {
        setSupportActionBar(mToolbar);
        getSupportActionBar().setDisplayShowTitleEnabled(false);
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        mToolbar.setNavigationIcon(R.mipmap.topback);
    }

    @Override
    protected void initView() {
        if (getIntent() != null) {
            mName = getIntent().getStringExtra("name");
            mTvName.setText(getString(R.string.payee, mName));
            double mLongitude = getIntent().getDoubleExtra("longitude", 0);
            double mDimensions = getIntent().getDoubleExtra("dimensions", 0);
            String mDistance = CommonTool.getDistanceKM(Double.parseDouble(MyApplication.getInstance().getLongitude()),
                    Double.parseDouble(MyApplication.getInstance().getLatitude()), mLongitude, mDimensions);
            if (DataUtil.moreThanOther(mDistance, "1")) {
                mTvDistance.setText(getString(R.string.distance, mDistance) + "km");
            } else {
                mTvDistance.setText(getString(R.string.distance, CommonTool.getDistanceOfM(Double.parseDouble(MyApplication.getInstance().getLongitude()),
                        Double.parseDouble(MyApplication.getInstance().getLatitude()), mLongitude, mDimensions)) + "m");
            }
            mMoney = getIntent().getStringExtra("money");
            mNotes = getIntent().getStringExtra("notes");
            mPaysecret = getIntent().getStringExtra("paysecret");
            mShopid = getIntent().getStringExtra("shopid");
            mTvSureMoney.setText(getString(R.string.to_pay, DataUtil.formatData(mMoney)));
            if (mMoney.contains(".")) {
                mMeidou = mMoney.substring(0, mMoney.indexOf("."));
            } else {
                mMeidou = mMoney;
            }
            mTvIncentiveMeidou.setText(mMeidou + " 美豆");
            if (DataUtil.moreThanZero(MyApplication.getInstance().getHdCurrency())) {
                mTvNoPay.setVisibility(View.GONE);
                mLlMeiDou.setVisibility(View.VISIBLE);
                if (DataUtil.moreThanOther(mMoney, "0")) {
                    String mHdCurrency = MyApplication.getInstance().getHdCurrency();
                    if (DataUtil.moreThanOther(mHdCurrency, mMoney)) {
                        if (mMoney.contains(".") && DataUtil.moreThanZero(mMoney.substring(mMoney.indexOf(".") + 1, mMoney.length()))) {
                            mRlSureMoey.setVisibility(View.VISIBLE);
                            mLlSecretPay.setVisibility(View.GONE);
                            hongdou = mMoney.substring(0, mMoney.indexOf("."));
                            money = DataUtil.subtract(mMoney, hongdou);
                        } else {
                            mRlSureMoey.setVisibility(View.GONE);
                            mLlSecretPay.setVisibility(View.VISIBLE);
                            hongdou = mMoney;
                            money = "0";
                        }
                    } else {
                        mRlSureMoey.setVisibility(View.VISIBLE);
                        mLlSecretPay.setVisibility(View.GONE);
                        if (mHdCurrency.contains(".") && DataUtil.moreThanZero(mHdCurrency.substring(mHdCurrency.indexOf(".") + 1, mHdCurrency.length()))) {
                            hongdou = mHdCurrency.substring(0, mHdCurrency.indexOf("."));
                        } else {
                            hongdou = mHdCurrency;
                        }
                        money = DataUtil.subtract(mMoney, hongdou);
                    }
                } else {
                    mTvNoPay.setVisibility(View.VISIBLE);
                    mLlMeiDou.setVisibility(View.GONE);
                    hongdou = "0";
                    money = mMoney;
                }
            } else {
                mRlSureMoey.setVisibility(View.VISIBLE);
                mLlSecretPay.setVisibility(View.GONE);
                mTvNoPay.setVisibility(View.VISIBLE);
                mLlMeiDou.setVisibility(View.GONE);
                hongdou = "0";
                money = mMoney;
            }

            String strhtml = "您现存<font color='#ff4c4c'>" + MyApplication.getInstance().getHdCurrency()
                    + "红豆</font>,将扣除<font color='#ff4c4c'>" + hongdou + "红豆</font>用于支付。";
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
                mTvHongdou.setText(Html.fromHtml(strhtml, Html.FROM_HTML_MODE_COMPACT));
            } else {
                mTvHongdou.setText(Html.fromHtml(strhtml));
            }
            mTvMoney.setText(DataUtil.formatData(money) + " 元");
            if (TextUtils.isEmpty(mNotes)) {
                mTvNotes.setVisibility(View.GONE);
            } else {
                mTvNotes.setVisibility(View.VISIBLE);
                mTvNotes.setText(getString(R.string.pay_notes, mNotes));
            }
        }
    }

    @OnClick({R.id.bt_sure_pay, R.id.tv_declare, R.id.iv_weixin, R.id.iv_zhifubao})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.bt_sure_pay:
                mTrim = mEtSecret.getText().toString().trim();
                if (TextUtils.isEmpty(mTrim)) {
                    ToastUtil.show(getString(R.string.input_yours));
                } else {
                    initNet(0);
                }
                break;
            case R.id.tv_declare:
                Intent intent = new Intent(UiUtils.getContext(), HtmlActivity.class);
                intent.putExtra("type", "doudouRule");
                startActivity(intent);
                break;
            case R.id.iv_weixin:
                if (CommonTool.isFirstLongScroll()) {
                    initNet(1);
                }
                break;
            case R.id.iv_zhifubao:
                if (CommonTool.isFirstLongScroll()) {
                    initNet(2);
                }
                break;
        }
    }

    /**
     * 解析后台返回的支付商户信息
     *
     * @param securityKey
     */
    private String parseSecutiryKey(String securityKey) {
        String jsonStr = "";
        try {
            String sourcestr = MD5Tool.Md5(MyApplication.getInstance().getSk() + MyApplication.getInstance().getNow());
            String str = URLDecoder.decode(securityKey, "UTF-8");
            jsonStr = DesTool.splitdecode(sourcestr, str);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return jsonStr;
    }


    private void initNet(final int i) {
        unsubscribe();
        mDisposable = NetWork.getOffLineApi()
                .getTokenApi(RelativeUrl.MYEXTENDINFO + MyApplication.getInstance().getUrl(), MyApplication.getInstance().getCheck(false))
                .flatMap(new Function<UserExtendResult, ObservableSource<PayInfo>>() {
                    @Override
                    public ObservableSource<PayInfo> apply(UserExtendResult userExtendResult) throws Exception {
                        MyApplication.getInstance().setSpValue(userExtendResult.getSafeobj());
                        return null;
                    }
                })
                .subscribeOn(Schedulers.io())
                .doOnSubscribe(new Consumer<Disposable>() {
                    @Override
                    public void accept(Disposable disposable) throws Exception {
                        showProgressDialog();
                    }
                })
                .subscribeOn(AndroidSchedulers.mainThread())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Consumer<PayInfo>() {
                    @Override
                    public void accept(PayInfo payInfo) throws Exception {
                        dismessProgressDialog();
                        MyApplication.getInstance().setSpValue(payInfo.safeobj);
                        if (!TextUtils.isEmpty(payInfo.checksum)) {
                            mChecksum = payInfo.checksum;
                        }
                        if (!TextUtils.isEmpty(payInfo.orderid)) {
                            mOrderid = payInfo.orderid;
                        }
                        if (!TextUtils.isEmpty(payInfo.ud)) {
                            mUd = payInfo.ud;
                        }
                        if (!TextUtils.isEmpty(payInfo.securityKey)) {
                            String mSecurityKey = payInfo.securityKey;
                            String payParams = parseSecutiryKey(mSecurityKey);
                            JSONObject jsonObject = new JSONObject(payParams);
                            JSONObject alipay = jsonObject.optJSONObject("alipay");
                            aliPayData = PayAliPayData.parseObject(alipay);
                            JSONObject wechat = jsonObject.optJSONObject("wechat");
                            weixinData = WeixinData.parseObject(wechat);
                        }
                        if (payInfo.code == 1) {
                            switch (i) {
                                case 0:  //纯红豆支付
                                    showPaySuccessDialog();
                                    break;
                                case 1:   //微信支付
                                    MyApplication.getInstance().sharedPrefrences.edit().putString("pay", "offline").commit();
                                    SpUtils.getInstance().saveSp("shopid", mShopid);
                                    SpUtils.getInstance().saveSp("mdffline", mMeidou);
                                    SpUtils.getInstance().saveSp("orderid", mOrderid);
                                    weixinPay();  //微信支付
                                    break;
                                case 2:   //支付宝支付
                                    MyApplication.getInstance().sharedPrefrences.edit().putString("pay", "offline").commit();
                                    zhifubaoPay();  //支付宝
                                    break;
                            }
                        } else if (payInfo.code == 4003) {
                            ToastUtil.show(getString(R.string.secret_error));
                        } else if (payInfo.code == 2816) {
                            logoutDialog();
                        } else {
                            ToastUtil.show(getString(R.string.loseData, payInfo.code));
                        }
                    }
                }, new Consumer<Throwable>() {
                    @Override
                    public void accept(Throwable throwable) throws Exception {
                        dismessProgressDialog();
                        ToastUtil.show(getString(R.string.load_error));
                    }
                });
    }

    private void logoutDialog() {
        final AlertDialog mDialog = new AlertDialog.Builder(this).create();
        View view = UiUtils.inflate(R.layout.dialog_logout);
        TextView tv_Iknow = (TextView) view.findViewById(R.id.tv_Iknow);
        tv_Iknow.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mDialog.dismiss();
                clearData();
            }
        });
        mDialog.setOnKeyListener(new DialogInterface.OnKeyListener() {
            @Override
            public boolean onKey(DialogInterface dialog, int keyCode, KeyEvent event) {
                if (keyCode == KeyEvent.KEYCODE_BACK && event.getAction() == KeyEvent.ACTION_DOWN) {
                    if (mDialog != null && mDialog.isShowing()) {
                        mDialog.dismiss();
                        clearData();
                    }
                    return true;
                }
                return false;
            }
        });
        mDialog.setCanceledOnTouchOutside(false);
        mDialog.setView(view);
        mDialog.show();
    }

    private void clearData() {
        if (null != MyApplication.getInstance().getUserId() || !"".equals(MyApplication.getInstance().getUserId())) {
            MyApplication.getInstance().sharedPrefrences.edit().putString("phone", "").commit();
            MyApplication.getInstance().sharedPrefrences.edit().putString("userid", "").commit();
            MyApplication.getInstance().sharedPrefrences.edit().putString("username", "").commit();
            MyApplication.getInstance().sharedPrefrences.edit().putString("shopname", "").commit();
            MyApplication.getInstance().sharedPrefrences.edit().putString("rmb", "").commit();
            MyApplication.getInstance().sharedPrefrences.edit().putString("silver", "").commit();
            MyApplication.getInstance().sharedPrefrences.edit().putString("inner", "").commit();
            MyApplication.getInstance().sharedPrefrences.edit().putString("hd", "").commit();
            MyApplication.getInstance().sharedPrefrences.edit().putString("num", "").commit();
            MyApplication.getInstance().sharedPrefrences.edit().putString("avatar", "").commit();
            MyApplication.getInstance().sharedPrefrences.edit().putBoolean("shareHolder", false).commit();
            MyApplication.getInstance().sharedPrefrences.edit().putBoolean("privilege", false).commit();
            MyApplication.getInstance().sharedPrefrences.edit().putString("avatar", "").commit();
            MyApplication.getInstance().sharedPrefrences.edit().putString("rewardName", "").commit();
            MyApplication.getInstance().sharedPrefrences.edit().putString("rewardUserphone", "").commit();
            MyApplication.getInstance().sharedPrefrences.edit().putString("rewardAddress", "").commit();
            MyApplication.getInstance().sharedPrefrences.edit().putString("rewardAddressid", "").commit();
            MyApplication.getInstance().sharedPrefrences.edit().putBoolean("beneficiary", false).commit();
            MyApplication.getInstance().sharedPrefrences.edit().putBoolean("merchants", false).commit();
            SpUtils.getInstance().saveSp("shopid", "");
            SpUtils.getInstance().saveSp("mdffline", "");
            SpUtils.getInstance().saveSp("orderid", "");
            finish();
            startActivity(new Intent(UiUtils.getContext(), MainHomeActivity.class));
        }
    }

    private void showPaySuccessDialog() {
        final AlertDialog mDialog = new AlertDialog.Builder(SurePayActivity.this).create();
        View view = UiUtils.inflate(R.layout.dialog_pay_success_offline);
        ImageView mImageVie = (ImageView) view.findViewById(R.id.iv_cancel);
        TextView tv_incentive_meidou = (TextView) view.findViewById(R.id.tv_incentive_meidou);
        final RatingBar mRatingBar = (RatingBar) view.findViewById(R.id.ratingBar);
        final EditText et_evaluate = (EditText) view.findViewById(R.id.et_evaluate);
        final TextView long_evaluate = (TextView) view.findViewById(R.id.long_evaluate);
        Button btn_reset = (Button) view.findViewById(R.id.btn_reset);
        Button btn_submit = (Button) view.findViewById(R.id.btn_submit);
        mImageVie.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                mDialog.dismiss();
                finish();
                startActivity(new Intent(UiUtils.getContext(), MainHomeActivity.class));
            }
        });
        tv_incentive_meidou.setText(mMoney + " 美豆");
        btn_reset.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                mRatingBar.setRating(0);
                et_evaluate.setText("");
            }
        });
        btn_submit.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                String mTrim = et_evaluate.getText().toString().trim();
                if (!TextUtils.isEmpty(mTrim) && mRatingBar.getRating() != 0) {
                    String rb = String.valueOf(mRatingBar.getRating());
                    addComment(mTrim, Integer.parseInt(rb.substring(0, rb.indexOf("."))));
                    mDialog.dismiss();
                    finish();
                    startActivity(new Intent(UiUtils.getContext(), MainHomeActivity.class));
                } else {
                    ToastUtil.show(getString(R.string.comment_nofinish));
                }
            }
        });
        et_evaluate.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
                long_evaluate.setText("0/200");
            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                long_evaluate.setText(s.length() + "/200");
            }
        });
        mDialog.setCanceledOnTouchOutside(false);
        mDialog.setOnKeyListener(new DialogInterface.OnKeyListener() {
            @Override
            public boolean onKey(DialogInterface dialogInterface, int i, KeyEvent keyEvent) {
                if (i == KeyEvent.KEYCODE_BACK && keyEvent.getAction() == KeyEvent.ACTION_DOWN) {
                    mDialog.dismiss();
                    finish();
                    startActivity(new Intent(UiUtils.getContext(), MainHomeActivity.class));
                    return true;
                }
                return false;
            }
        });
        mDialog.setView(view);
        mDialog.show();
    }

    private void addComment(String trim, int rating) {
        unsubscribe();
        mDisposable = NetWork.getOffLineApi().addCommentApi(RelativeUrl.ADDCOMMENT + MyApplication.getInstance().getUrl(),
                MyApplication.getInstance().getCheck(false), mShopid, mOrderid, rating, trim)
                .subscribeOn(Schedulers.io())
                .doOnSubscribe(new Consumer<Disposable>() {
                    @Override
                    public void accept(Disposable disposable) throws Exception {
                        showProgressDialog();
                    }
                })
                .subscribeOn(AndroidSchedulers.mainThread())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Consumer<BaseResponse>() {
                    @Override
                    public void accept(BaseResponse baseResponse) throws Exception {
                        dismessProgressDialog();
                        MyApplication.getInstance().setSpValue(baseResponse.getSafeobj());
                        if (baseResponse.getCode() != 1) {
                            ToastUtil.show(getString(R.string.losePay, baseResponse.getCode()));
                        } else {
                            finish();
                            startActivity(new Intent(UiUtils.getContext(), MainHomeActivity.class));
                        }
                    }
                }, new Consumer<Throwable>() {
                    @Override
                    public void accept(Throwable throwable) throws Exception {
                        dismessProgressDialog();
                        ToastUtil.show(getString(R.string.load_error));
                    }
                });
    }

    private IWXAPI msgApi;
    private PayReq req;
    private StringBuffer sb;
    private Map<String, String> resultunifiedorder;

    private void weixinPay() {
        msgApi = WXAPIFactory.createWXAPI(UiUtils.getContext(), weixinData.getAppid());
        // 将该app注册到微信
        msgApi.registerApp(weixinData.getAppid());
        getWXOrderInfo();
    }


    /**
     * 获取微信支付订单
     */
    private void getWXOrderInfo() {
        //正常情况下，请求服务器获取订单参数
        req = new PayReq();
        sb = new StringBuffer();
        GetPrepayIdTask getPrepayId = new GetPrepayIdTask();
        getPrepayId.execute();
    }

    private class GetPrepayIdTask extends AsyncTask<Void, Void, Map<String, String>> {

        private ProgressDialog dialog;

        @Override
        protected void onPreExecute() {
            dialog = ProgressDialog.show(SurePayActivity.this, getString(R.string.app_tip), getString(R.string.getting_prepayid));
        }

        @Override
        protected void onPostExecute(Map<String, String> result) {
            if (dialog != null) {
                dialog.dismiss();
            }
            sb.append("prepay_id\n" + result.get("prepay_id") + "\n\n");
            resultunifiedorder = result;
            genPayReq();
        }

        @Override
        protected void onCancelled() {
            super.onCancelled();
        }

        @Override
        protected Map<String, String> doInBackground(Void... params) {

            String url = String.format("https://api.mch.weixin.qq.com/pay/unifiedorder");
            String entity = genProductArgs();

            byte[] buf = Util.httpPost(url, entity);

            String content = new String(buf);
            Log.e("orion", content);
            Map<String, String> xml = decodeXml(content);

            return xml;
        }

    }

    private void genPayReq() {

        req.appId = weixinData.getAppid();
        req.partnerId = weixinData.getSeller();
        req.prepayId = resultunifiedorder.get("prepay_id");
        req.packageValue = "Sign=WXPay";
        req.nonceStr = genNonceStr();
        req.timeStamp = String.valueOf(genTimeStamp());


        List<NameValuePair> signParams = new LinkedList<NameValuePair>();
        signParams.add(new BasicNameValuePair("appid", req.appId));
        signParams.add(new BasicNameValuePair("noncestr", req.nonceStr));
        signParams.add(new BasicNameValuePair("package", req.packageValue));
        signParams.add(new BasicNameValuePair("partnerid", req.partnerId));
        signParams.add(new BasicNameValuePair("prepayid", req.prepayId));
        signParams.add(new BasicNameValuePair("timestamp", req.timeStamp));

        req.sign = genAppSign(signParams);

        sb.append("sign\n" + req.sign + "\n\n");

        Log.e("orion", signParams.toString());

        msgApi.sendReq(req);

    }

    private String genAppSign(List<NameValuePair> params) {
        StringBuilder sb = new StringBuilder();

        for (int i = 0; i < params.size(); i++) {
            sb.append(params.get(i).getName());
            sb.append('=');
            sb.append(params.get(i).getValue());
            sb.append('&');
        }
        sb.append("key=");
        sb.append(weixinData.getPartner());

        this.sb.append("sign str\n" + sb.toString() + "\n\n");
        String appSign = MD5.getMessageDigest(sb.toString().getBytes()).toUpperCase();
        Log.e("orion", appSign);
        return appSign;
    }

    private String genOutTradNo() {
        Random random = new Random();
        return MD5.getMessageDigest(String.valueOf(random.nextInt(10000)).getBytes());
    }

    private String genProductArgs() {
        StringBuffer xml = new StringBuffer();
        try {
            String nonceStr = genNonceStr();
            String trade = "";
            if ((mOrderid + genOutTradNo()).length() > 32) {
                trade = (mOrderid + genOutTradNo()).substring(0, 32);
            } else {
                trade = mOrderid + genOutTradNo();
            }
            xml.append("</xml>");
            List<NameValuePair> packageParams = new LinkedList<NameValuePair>();
            packageParams.add(new BasicNameValuePair("appid", weixinData.getAppid()));
            packageParams.add(new BasicNameValuePair("attach", getTimeValue() + "||" + MyApplication.getInstance().getUserId()
                    + "||" + mOrderid + "||5||" + hongdou + "," + money + "," + mUd));
            packageParams.add(new BasicNameValuePair("body", mName));
            packageParams.add(new BasicNameValuePair("mch_id", weixinData.getSeller()));
            packageParams.add(new BasicNameValuePair("nonce_str", nonceStr));
            packageParams.add(new BasicNameValuePair("notify_url", Url.BASE_URL + "/notify/pay/wepay"));  //wepay
            packageParams.add(new BasicNameValuePair("out_trade_no", trade));
            packageParams.add(new BasicNameValuePair("spbill_create_ip", MyApplication.getInstance().getLocalIPAddress()));
            BigDecimal bd = new BigDecimal(money);
            packageParams.add(new BasicNameValuePair("total_fee", bd.multiply(new BigDecimal(100)).intValue() + ""));
            packageParams.add(new BasicNameValuePair("trade_type", "APP"));

            String sign = genPackageSign(packageParams);
            packageParams.add(new BasicNameValuePair("sign", sign));

            String xmlstring = toXml(packageParams);
            return new String(xmlstring.toString().getBytes(), "ISO8859-1");
        } catch (Exception e) {
            return null;
        }
    }

    private String toXml(List<NameValuePair> params) {
        StringBuilder sb = new StringBuilder();
        sb.append("<xml>");
        for (int i = 0; i < params.size(); i++) {
            sb.append("<" + params.get(i).getName() + ">");


            sb.append(params.get(i).getValue());
            sb.append("</" + params.get(i).getName() + ">");
        }
        sb.append("</xml>");

        Log.e("orion", sb.toString());
        return sb.toString();
    }

    public Map<String, String> decodeXml(String content) {
        try {
            Map<String, String> xml = new HashMap<String, String>();
            XmlPullParser parser = Xml.newPullParser();
            parser.setInput(new StringReader(content));
            int event = parser.getEventType();
            while (event != XmlPullParser.END_DOCUMENT) {

                String nodeName = parser.getName();
                switch (event) {
                    case XmlPullParser.START_DOCUMENT:

                        break;
                    case XmlPullParser.START_TAG:

                        if ("xml".equals(nodeName) == false) {
                            //实例化student对象
                            xml.put(nodeName, parser.nextText());
                        }
                        break;
                    case XmlPullParser.END_TAG:
                        break;
                }
                event = parser.next();
            }

            return xml;
        } catch (Exception e) {
            Log.e("orion", e.toString());
        }
        return null;

    }

    private String genNonceStr() {
        Random random = new Random();
        return MD5.getMessageDigest(String.valueOf(random.nextInt(10000)).getBytes());
    }

    private long genTimeStamp() {
        return System.currentTimeMillis() / 1000;
    }

    /**
     * 生成签名（微信）
     */

    private String genPackageSign(List<NameValuePair> params) {
        StringBuilder sb = new StringBuilder();

        for (int i = 0; i < params.size(); i++) {
            sb.append(params.get(i).getName());
            sb.append('=');
            sb.append(params.get(i).getValue());
            sb.append('&');
        }
        sb.append("key=");
        sb.append(weixinData.getPartner());

        String packageSign = MD5.getMessageDigest(sb.toString().getBytes()).toUpperCase();
        Log.e("orion", packageSign);
        return packageSign;
    }


    private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case 0:
                    PayResult payResult = new PayResult((String) msg.obj);
                    /**
                     * 对于支付结果，请商户依赖服务端的一部通知结果。同步通知结果，仅作为支付结束的通知。
                     */
                    String resultInfo = payResult.getResult();//同步返回需要验证的信息
                    String resultStatus = payResult.getResultStatus();
                    //判断resultStatus为9000则代表支付成功
                    if (TextUtils.equals(resultStatus, "9000")) {
                        //该笔订单是否真实支付成功，需要依赖服务端的异步通知
                        Intent intent = new Intent(UiUtils.getContext(), PaySuccessActivity.class);
                        intent.putExtra("status", 1);
                        intent.putExtra("shopid", mShopid);
                        intent.putExtra("redbeen", mMeidou);
                        intent.putExtra("orderid", mOrderid);
                        startActivity(intent);
                    } else {
                        startActivity(new Intent(UiUtils.getContext(), PaySuccessActivity.class));
                    }
                    break;
            }
        }
    };

    private void zhifubaoPay() {
        String orderInfo = getOrderInfo(aliPayData);
        //  特别注意，这里的签名逻辑需要放在服务端，切勿将私钥泄露在代码中

        String sign = sign(orderInfo, aliPayData.getRsaPrivate());
        try {
            //仅需对sign做URL编码
            sign = URLEncoder.encode(sign, "UTF-8");
        } catch (Exception e) {
            e.printStackTrace();
        }
        //完整的符合支付宝参数规范的订单信息
        final String payInfo = orderInfo + "&sign=\"" + sign + "\"&" + getSignType();

        Runnable payRunnable = new Runnable() {
            @Override
            public void run() {
                // 构造PayTask 对象
                PayTask alipay = new PayTask(SurePayActivity.this);
                // 调用支付接口，获取支付结果
                String result = alipay.pay(payInfo, true);

                Message msg = new Message();
                msg.what = 0;
                msg.obj = result;
                mHandler.sendMessage(msg);
            }
        };

        // 必须异步调用
        Thread payThread = new Thread(payRunnable);
        payThread.start();
    }

    // create the order info. 创建订单信息（支付宝）
    private String getOrderInfo(PayAliPayData alipay) {

        String trade = "";

        if ((mOrderid + genOutTradNo()).length() > 32) {
            trade = (mOrderid + genOutTradNo()).substring(0, 32);
        } else {
            trade = mOrderid + genOutTradNo();
        }

        // 签约合作者身份ID
        String orderInfo = "partner=" + "\"" + alipay.getPartner() + "\"";

        // 签约卖家支付宝账号
        orderInfo += "&seller_id=" + "\"" + alipay.getSeller() + "\"";

        // 商户网站唯一订单号
        orderInfo += "&out_trade_no=" + "\"" + trade + "\"";

        // 商品名称
        orderInfo += "&subject=" + "\"" + mName + "\"";

        // 商品详情
        orderInfo += "&body=" + "\"" + getTimeValue() + "||" + MyApplication.getInstance().getUserId()
                + "||" + mOrderid + "||5||" + hongdou + "," + money + "," + mUd + "\"";

        // 商品金额
        orderInfo += "&total_fee=" + "\"" + money + "\"";

        // 服务器异步通知页面路径
        orderInfo += "&notify_url=" + "\"" + Url.BASE_URL + "/notify/pay/alipay" + "\"";   //api3

        // 服务接口名称， 固定值
        orderInfo += "&service=\"mobile.securitypay.pay\"";

        // 支付类型， 固定值
        orderInfo += "&payment_type=\"1\"";

        // 参数编码， 固定值
        orderInfo += "&_input_charset=\"utf-8\"";

        // 设置未付款交易的超时时间
        // 默认30分钟，一旦超时，该笔交易就会自动被关闭。
        // 取值范围：1m～15d。
        // m-分钟，h-小时，d-天，1c-当天（无论交易何时创建，都在0点关闭）。
        // 该参数数值不接受小数点，如1.5h，可转换为90m。
        orderInfo += "&it_b_pay=\"30m\"";

        // extern_token为经过快登授权获取到的alipay_open_id,带上此参数用户将使用授权的账户进行支付
        // orderInfo += "&extern_token=" + "\"" + extern_token + "\"";

        // 支付宝处理完请求后，当前页面跳转到商户指定页面的路径，可空
        orderInfo += "&return_url=\"" + Url.BASE_URL + "\"";

        return orderInfo;
    }

    /**
     * sign the order info. 对订单信息进行签名（支付宝）
     *
     * @param content 待签名订单信息
     */
    private String sign(String content, String rsa_private) {
        return SignUtils.sign(content, rsa_private);
    }

    /**
     * get the sign type we use. 获取签名方式（支付宝）
     */
    private String getSignType() {
        return "sign_type=\"RSA\"";
    }

    /**
     * 获取当前时间戳
     *
     * @return
     */
    private String getTimeValue() {
        Date date = new Date();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
        String str = sdf.format(date);
        return str;
    }
}
